package logic

import (
	"context"
	"fmt"
	"retailers/model/mysql"
	"retailers/model/redis"
	"retailers/pkg"

	"retailers/retailersrpc/internal/svc"
	"retailers/retailersrpc/retailersrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UtdatepasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUtdatepasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UtdatepasswordLogic {
	return &UtdatepasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UtdatepasswordLogic) Utdatepassword(in *retailersrpc.UtdatepasswordRequest) (*retailersrpc.UtdatepasswordResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Client.Get("Captchaupdate" + in.Phone)
	if get.Val() != in.Code {
		return nil, fmt.Errorf("图形验证码输入错误请重新输入")
	}
	cmd := redis.Client.Get("sendSmsupdate" + in.Phone)
	if cmd.Val() != in.Sms {
		return nil, fmt.Errorf("短信验证码输入错误请重新输入")
	}
	var finduser mysql.User
	mysql.DB.Debug().Where("phone = ?" + in.Phone).Find(&finduser)
	if finduser.ID == 0 {
		return nil, fmt.Errorf("没有该账号请重新输入")
	}
	if finduser.Password != pkg.Md5password(in.Password) {
		return nil, fmt.Errorf("老密码不一致请重新输入")
	}
	if finduser.Password == pkg.Md5password(in.Password) {
		return nil, fmt.Errorf("新旧密码不一致请重新输入")
	}
	if finduser.Password != pkg.Md5password(in.Newpassword) {
		return nil, fmt.Errorf("确认密码不一致请重新输入")
	}
	in.Password = pkg.Md5password(in.Newpassword)
	mysql.DB.Debug().Updates(&finduser)
	redis.Client.Del("Captchaupdate" + in.Phone)
	redis.Client.Del("sendSmsupdate" + in.Phone)
	return &retailersrpc.UtdatepasswordResponse{Id: int64(finduser.ID)}, nil
}
